﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using mshtml;
using System.Collections;
using System.Threading;
using HtmlAgilityPack;
using log4net;

namespace CapchaUserControl
{
    
    public partial class CapchaUserControl: UserControl
    {
        ILog log = LogManager.GetLogger(typeof(CapchaUserControl)); 
        public CapchaUserControl()
        {
            InitializeComponent();
            
        }

        string webId;
        public static string keyWord_xpath = "%";
        string human = "";

        public string WebId
        {
            get { return webId; }
            set { webId = value; }
        }
        private ISending listener;

        public ISending Listener
        {
            get { return listener; }
            set { listener = value; }
        }

        public CapchaUserControl(string webId,ISending listener)
        {
            log.Info("Khoi tao 1 CapchaUserControl");

            InitializeComponent();  
            this.webId = webId;
            this.listener = listener;
        }

        public TextBox getTextBox()
        {
            return txtCapcha;
        }

        public WebBrowser getWebBrowser()
        {
            return webBrowser1;
        }

        public void setTextBoxFocus()
        {
            txtCapcha.Focus();
        }

        public void keyEnter()
        {
            listener.onSending(webId, txtCapcha.Text, human);
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            listener.onSending(webId, txtCapcha.Text, human);
        }

        public void LoadCapcha(string _htmlString, string _xpath, string _human)
        {
            human = _human;

            if (_htmlString == "")
            {
                return;
            }
            webBrowser1.DocumentText = _htmlString;
            webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;

            //string[] arr = xpath.Split(new string[] { keyWord_xpath }, StringSplitOptions.None);
            
        }

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (human != "")
            {
                HtmlElementCollection col = webBrowser1.Document.GetElementsByTagName("input").GetElementsByName(human);
                foreach (HtmlElement ele in col)
                {
                    human = ele.GetAttribute("value");
                    break;
                }
            }
        
        }
    }
}
